package com.minglead.springboot.platform.sys.service;

import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.minglead.springboot.common.crud.CrudService;
import com.minglead.springboot.common.persistence.Page;
import com.minglead.springboot.common.utils.StringUtils;
import com.minglead.springboot.platform.sys.utils.UserUtils;
import com.minglead.springboot.platform.sys.dao.AreaDao;
import com.minglead.springboot.platform.sys.entity.Area;



/**
 * 区域Service
 */
@Service
@Transactional(readOnly = true)
public class AreaService extends CrudService<AreaDao, Area>{

	public Area get(String id){
		return super.get(id);
	} 
	
	public List<Area> findAll(){
		return UserUtils.getAreaList();
	}
	
	public Page<Area> findPage(Page<Area> page,Area area){
		area.setPage(page);
		List<Area> list=dao.findAllList(area);
		for(Area item:list){
			item.setTypeValue(Area.getTypeLabel(item.getType()));
		}
		page.setList(list);
		return page;
	}

	@Transactional(readOnly = false)
	public void save(Area area) {
		super.save(area);
		UserUtils.removeCache(UserUtils.CACHE_AREA_LIST);
	}
	
	@Transactional(readOnly = false)
	public void delete(Area area) {
		super.delete(area);
		UserUtils.removeCache(UserUtils.CACHE_AREA_LIST);
	}
	
	public List<Area> getSubListByCode(String code){
		return dao.getSubListByCode(code);
	}
	
	/**
	 * 为了解决中山、东莞这些无下级区的地级市，必须允许dao.getEntityByCode 返回多条记录，code 可以重复。
	 * @param code
	 * @return
	 */
	public Area getEntityByCode(String code){
		return dao.getEntityByCode(code);
	}
	

	public List<Area> getSubListByParentId(String parentId){
		return dao.getSubListByParentId(parentId);
	}

	/**
	 * 获取根节点
	 * @return
	 */
	public Area getRoot(){
		return dao.getRoot();
	}
	
	/**
	 * 根据ID取多级的区域列表
	 * @param id
	 * @return
	 */
	public List<Area> getTreeLevelsList(String id){
		return dao.getTreeLevelsList(id);
	}
	
	public Area getTreeLevelsListByType(String id,String type){
		return dao.getTreeLevelsListByType(id,type);
	}
	
	/**
	 * 根据区划编码获取  xxx省xxx市xxx区/县  的字符串
	 * @param areaCode
	 * @return
	 */
	public String getAreaStr(String areaCode){
		String areaStr = "";
		if(StringUtils.isNotBlank(areaCode)){
			Area area = getEntityByCode(areaCode);
			if(area!=null){
				List<Area> areaList = getTreeLevelsList(area.getId());
				String o_province = "";
				String o_city = "";
				String o_area = "";
				for(Area a:areaList){
					if("2".equals(a.getType())){					
						o_province = a.getName();
					}else if("3".equals(a.getType())){
						o_city = a.getName();
						if("市辖区".equals(a.getName())){
							//a = areaService.getTreeLevelsListByType(a.getId(),"2");
							o_city = "";
						}
					}else if("4".equals(a.getType())){
						o_area = a.getName();
					}
				}
				areaStr = o_province + o_city + o_area;
			}
		}
		return areaStr;
	}
}
